package com.yangyang.androidconnect.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.yangyang.androidconnect.vo.response.FileInfo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FileIndexDao {
    private static final String TAG = "FileIndexDao";
    private final FileIndexDbHelper dbHelper;

    public FileIndexDao(Context context) {
        dbHelper = new FileIndexDbHelper(context);
    }

    // 插入或更新文件信息
    public void insertOrUpdateFile(File file, String parentPath) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(FileIndexDbHelper.COLUMN_PATH, file.getAbsolutePath());
        values.put(FileIndexDbHelper.COLUMN_NAME, file.getName());
        values.put(FileIndexDbHelper.COLUMN_IS_FILE, file.isFile() ? 1 : 0);
        values.put(FileIndexDbHelper.COLUMN_SIZE, file.length());
        values.put(FileIndexDbHelper.COLUMN_CREATION_TIME, file.lastModified()); // 注意：Android没有直接获取创建时间的API
        values.put(FileIndexDbHelper.COLUMN_LAST_MODIFIED, file.lastModified());
        values.put(FileIndexDbHelper.COLUMN_PARENT_PATH, parentPath);

        // 获取文件扩展名
        String name = file.getName();
        int dotIndex = name.lastIndexOf('.');
        if (dotIndex > 0) {
            String extension = name.substring(dotIndex + 1).toLowerCase();
            values.put(FileIndexDbHelper.COLUMN_EXTENSION, extension);
        }

        try {
            db.insertWithOnConflict(FileIndexDbHelper.TABLE_FILES, null, values,
                    SQLiteDatabase.CONFLICT_REPLACE);
        } catch (Exception e) {
            Log.e(TAG, "Error inserting file: " + file.getAbsolutePath(), e);
        } finally {
            db.close();
        }
    }

    // 删除文件记录
    public void deleteFile(String filePath) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        try {
            db.delete(FileIndexDbHelper.TABLE_FILES,
                    FileIndexDbHelper.COLUMN_PATH + " = ?", new String[]{filePath});
        } catch (Exception e) {
            Log.e(TAG, "Error deleting file: " + filePath, e);
        } finally {
            db.close();
        }
    }

    // 根据父路径查询文件列表（分页）
    public List<FileInfo> getFilesByParentPath(String parentPath, int page, int pageSize,
                                               String sortBy, boolean ascending) {
        List<FileInfo> fileList = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        int offset = (page - 1) * pageSize;
        String orderBy = sortBy + (ascending ? " ASC" : " DESC");

        String selection = FileIndexDbHelper.COLUMN_PARENT_PATH + " = ?";
        String[] selectionArgs = {parentPath};

        Cursor cursor = null;
        try {
            cursor = db.query(FileIndexDbHelper.TABLE_FILES,
                    null, selection, selectionArgs, null, null, orderBy,
                    pageSize + " OFFSET " + offset);

            while (cursor != null && cursor.moveToNext()) {
                FileInfo info = cursorToFileInfo(cursor);
                fileList.add(info);
            }
        } catch (Exception e) {
            Log.e(TAG, "Error querying files", e);
        } finally {
            if (cursor != null) cursor.close();
            db.close();
        }

        return fileList;
    }

    // 获取指定目录下的文件总数
    public int getFileCount(String parentPath) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        int count = 0;

        String selection = FileIndexDbHelper.COLUMN_PARENT_PATH + " = ?";
        String[] selectionArgs = {parentPath};

        Cursor cursor = null;
        try {
            cursor = db.query(FileIndexDbHelper.TABLE_FILES,
                    new String[]{"COUNT(*)"}, selection, selectionArgs, null, null, null);

            if (cursor != null && cursor.moveToFirst()) {
                count = cursor.getInt(0);
            }
        } catch (Exception e) {
            Log.e(TAG, "Error getting file count", e);
        } finally {
            if (cursor != null) cursor.close();
            db.close();
        }

        return count;
    }

    // 清空表
    public void clearAll() {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        try {
            db.delete(FileIndexDbHelper.TABLE_FILES, null, null);
        } catch (Exception e) {
            Log.e(TAG, "Error clearing table", e);
        } finally {
            db.close();
        }
    }

    // 从Cursor转换为FileInfo
    private FileInfo cursorToFileInfo(Cursor cursor) {
        FileInfo info = new FileInfo();

        int isFileIndex = cursor.getColumnIndex(FileIndexDbHelper.COLUMN_IS_FILE);
        int nameIndex = cursor.getColumnIndex(FileIndexDbHelper.COLUMN_NAME);
        int pathIndex = cursor.getColumnIndex(FileIndexDbHelper.COLUMN_PATH);
        int creationTimeIndex = cursor.getColumnIndex(FileIndexDbHelper.COLUMN_CREATION_TIME);
        int lastModifiedIndex = cursor.getColumnIndex(FileIndexDbHelper.COLUMN_LAST_MODIFIED);

        info.setIsFile(cursor.getInt(isFileIndex) == 1);
        info.setName(cursor.getString(nameIndex));
        info.setFullName(cursor.getString(pathIndex));

        long creationTime = cursor.getLong(creationTimeIndex);
        long lastModified = cursor.getLong(lastModifiedIndex);

        // 转换为字符串格式的时间
        info.setCreationTime(formatTimestamp(creationTime));
        info.setLastModifiedTime(formatTimestamp(lastModified));

        return info;
    }

    // 时间戳格式化方法
    private String formatTimestamp(long timestamp) {
        if (timestamp == 0) return "";
        return new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault())
                .format(new java.util.Date(timestamp));
    }
}